//
//  STWebViewController.m
//  SportHome
//
//  Created by stoneobs on 16/12/14.
//  Copyright © 2016年 stoneobs. All rights reserved.
//

#import "KLSepeedBuyViewController.h"
#import <WebKit/WebKit.h>
@interface KLSepeedBuyViewController ()<WKNavigationDelegate>
@property(nonatomic, strong) NSString             *urlStr;
@property(nonatomic, strong) NSString             *h5String;
@property(nonatomic, strong) WKWebView            *webView;
@property(nonatomic, strong) UIProgressView       *progressView;
@property(nonatomic, strong) UIView               *loadingView;
@end

@implementation KLSepeedBuyViewController

- (instancetype)initWithUrl:(NSString *)url
{
    self = [super init];
    if (self) {
        self.urlStr = url;
    }
    return self;
}
- (instancetype)initWithH5String:(NSString *)h5String{
    self = [super init];
    if (self) {
        self.h5String = h5String;
    }
    return self;
}
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}
#pragma mark --Geter And Setter
- (UIColor *)progressTintColor
{
    if (_progressTintColor) {
        return _progressTintColor;
    }
    return [UIColor orangeColor];
}
- (UIColor *)progressBackgroundColor
{
    if (_progressTintColor) {
        return _progressTintColor;
    }
    return [UIColor grayColor];
}
#pragma mark --vc生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    [self sendDesRequest];
    self.title = @"匀加速购买";
    self.view.backgroundColor = [UIColor whiteColor];
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, UIScreenHeight - 50)];
    [self.view addSubview:self.webView];
    
    __weak typeof(self) weakSelf =  self;
    STButton * buyButton = [[STButton alloc] initWithFrame:CGRectMake(0, self.webView.bottom, UIScreenWidth, 50)
                                                     title:@"上传折扣图片"
                                                titleColor:[UIColor whiteColor]
                                                 titleFont:18
                                              cornerRadius:0
                                           backgroundColor:KL_BlueBackGroundColor
                                           backgroundImage:nil
                                                     image:nil];
    buyButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
    [buyButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelcetedBuyButtton];
    }];
    [self.view addSubview:buyButton];
    
    
    if (self.urlStr) {
        [self.webView loadRequest:[[NSURLRequest alloc] initWithURL:[NSURL URLWithString:self.urlStr]]];
    }
    if (self.h5String) {
        [self.webView loadHTMLString:self.h5String baseURL:nil];
    }
    
    self.webView.navigationDelegate = self;
    
    
    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 64, SCREEN_WIDTH, 1)];
    self.progressView.backgroundColor = self.progressBackgroundColor;
    self.progressView.progressTintColor = self.progressTintColor;
    [self.view addSubview:self.progressView];
    
    if (!self.navigationController.navigationController.navigationBar.translucent) {
        self.progressView.frame = CGRectMake(0, 0, SCREEN_WIDTH, 1);
        //self.webView.height = self.webView.height - 64;
    }else{
        self.progressView.frame = CGRectMake(0, 64, SCREEN_WIDTH, 1);
        
    }
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
    
    //菊花
    UIActivityIndicatorView * juhuaView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [juhuaView startAnimating];
    self.loadingView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 80, 80)];
    juhuaView.center = CGPointMake(_loadingView.frame.size.width/2, _loadingView.frame.size.width/2);
    self.loadingView.layer.cornerRadius = 15;
    self.loadingView.center = self.view.center;
    self.loadingView.backgroundColor = [UIColor grayColor];
    [self.loadingView addSubview:juhuaView];
    [self.view addSubview:self.loadingView];
}
- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    
}
- (void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
}
#pragma mark --kvo
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if (object==self.webView&&[keyPath isEqualToString:@"estimatedProgress"]) {
        //NSLog(@"%f",self.webView.estimatedProgress);
        self.progressView.progress = self.webView.estimatedProgress;
        
    }
    if (object==self.webView&&[keyPath isEqualToString:@"title"]) {
        
        self.title = self.webView.title;
    }
}
#pragma mark --WKNavigationDelegate

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    
    //完成
    self.loadingView.hidden = YES;
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    
}
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error
{
    self.loadingView.hidden = YES;
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    NSLog(@"%@",error);
    
    
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
{
    
    self.loadingView.hidden = YES;
    NSLog(@"%@",error);
    if (self.forceTitle.length) {
        self.title = self.forceTitle;
    }
    
}
#pragma mark --Action Method
- (void)onSelcetedBuyButtton{
    
    //生成订单
    [self showDefultImagePicker:^(UIImage *image) {
        [SVProgressHUD showWithStatus:@"请稍后"];
        [self sendSaveOrderRequestWithSuccess:^(BOOL isSuccess, NSString *oriderID) {
            if (isSuccess) {
                [KLUtils sendQiNiuWithImage:image handle:^(NSString *imageUrl, NSString *errorDes) {
                    //上传图片
                    [self sendBuySpeedRequestWithID:oriderID screenshot:imageUrl];
                }];
            }
        }];

    }];
    


    
}
- (void)sendDesRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/screenshot/explain",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                
                                                 [SVProgressHUD dismiss];
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 NSLog(@"json = %@",dataDic.mj_JSONString);
                                                 if ([dataDic.allKeys containsObject:@"info"]) {
                                                     self.h5String  = dataDic[@"info"];
                                                     if (self.h5String) {
                                                         [self.webView loadHTMLString:self.h5String baseURL:nil];
                                                     }
                                                 }
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                                 
                                             }];
}
- (void)sendSaveOrderRequestWithSuccess:(void(^)(BOOL isSuccess,NSString * oriderID)) handle{
    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:self.model.goodID forKey:@"goods_id"];
    [dic setObject:self.model.shops_id forKey:@"shop_id"];
    
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/screenshot/addorder",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                NSDictionary * dataDic =  responseObject[@"data"];
                                                 NSString * orderID = dataDic[@"screenshot_id"];
                                                 if (handle) {
                                                     handle(YES,orderID);
                                                 }
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 if (handle) {
                                                     handle(NO,@"");
                                                 }
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
    
}
- (void)sendBuySpeedRequestWithID:(NSString*)orderID  screenshot:(NSString*)imageUrl{

    NSMutableDictionary * dic = [NSMutableDictionary new];
    [dic setObject:orderID forKey:@"screenshot_id"];
    [dic setObject:imageUrl forKey:@"screenshot"];
    
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/screenshot/updatescreenshot",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                                                 
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                             }];
}
@end

